<?php

namespace Admin\Controller;

class UrlController extends CommonController
{
    public function _initialize()
    {
        parent::_initialize();
        $config = D('Config')->get_config();
        $this->assign('show', $config);
        ytata_refresh_cache('url');
    }

    public function lists()
    {
        $map = array();
        $url = D('Url')->get_list($map, true, '', '');
        $this->assign('url', $url);
        $this->display();
    }

    public function allsave()
    {
        $id         = I('post.id');
        $alias      = I('post.alias');
        $locator    = I('post.locator');
        $rule_key   = I('post.rule_key');
        $rule_var   = I('post.rule_var');
        $is_display = I('post.is_display');
        $num        = 0;
        $data       = M("Url");
        if (is_array($id) && count($id) > 0) {
            foreach ($id as $k => $v) {
                unset($map);
                $map['id']         = intval($v);
                $map['alias']      = trim($alias[$k]);
                $map['locator']    = trim($locator[$k]);
                $map['rule_key']   = trim($rule_key[$k]);
                $map['rule_var']   = trim($rule_var[$k]);
                $map['is_display'] = intval($is_display[$k]);
                $data->save($map);
                $num++;

            }
        }
        if ($num > 0) {
            ytata_refresh_cache('url');
            $this->success('成功保存' . $num . '条信息！');
        } else {
            $this->error('未保存任何信息！');
        }
    }

    public function add()
    {
        if (IS_POST) {
            $data = D("Url");
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->add();
                $this->success('保存完成', 'lists');
            }
        } else {
            $this->display();
        }
    }

    public function edit()
    {
        if (IS_POST) {
            $data = D("Url");
            if (!$data->create()) {
                $this->error($data->getError());
            } else {
                $data->save();
                $this->success('保存完成', 'lists');
            }
        } else {
            $id = I('get.id', '', 'intval');
            if ($id) {
                $data      = M("Url");
                $map['id'] = $id;
                $show      = $data->where($map)->find();
                $this->assign('show', $show);
                $this->display();
            } else {
                $this->error('非法请求');
            }
        }
    }

    public function delete()
    {
        $ids = I('request.id');
        $ids = is_array($ids) ? implode(",", $ids) : $ids;
        if ($ids && preg_match("/^(\d{1,10},)*(\d{1,10})$/", $ids)) {
            $data = M("Url");
            $s    = $data->delete($ids);
            $this->success("成功删除{$s}条数据");
        } else {
            $this->error('请选择要删除的信息！');
        }
    }
}